package com.aphrodite.ui.widgets;

import java.util.Timer;
import java.util.TimerTask;

/**
 * High level abstraction of text effect widgets.
 * <p>
 * Text effects are never started by default. we need to call the
 * {@link TextEffect#start()} to start any of the Widgets that are children of a
 * text effect.
 * </p>
 * 
 * @author kentelt
 * 
 */
abstract class TextEffect extends Widget {

	private final class Ani extends TimerTask {
		public final void run() {
			while (doEffect) {
				doAniTask();
				reDrawWidget();
				/* Animation sleep interval */
				try {
					Thread.sleep(effectInterval);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

			}
			doPostAniTask();
		}
	}

	boolean doEffect;

	int effectInterval = 200;
	String text;

	private Timer timer;

	TextEffect(Theme theme, int width, int height) {
		super(theme, width, height);
	}

	abstract void doAniTask();

	/* Dummy extension */
	void doPostAniTask() {}

	/**
	 * Checks to see if the effect is running
	 * 
	 * @return <code>true</code> if the effect is in progress
	 */
	public boolean isRunning() {
		return doEffect;
	}

	public synchronized void setAnimationInterval(int interval) {
		this.effectInterval = interval;
	}

	/**
	 * Set the text that is used by this widget
	 * 
	 * @param text
	 */
	public synchronized void setText(String text) {
		this.text = text;
		updateModel();
		reDraw();
		stateChanged(this);
	}

	public void setTitle(String title) {

	}

	public void setVisible(boolean isVisible) {
		super.setVisible(isVisible);
		/* Stop bg threads when not visible */
		if (!isVisible) {
			stop();
		} else {
			start();
		}
	}

	/**
	 * Starts the text effect
	 */
	public synchronized void start() {
		if (!doEffect) {
			doEffect = true;
			timer = new Timer();
			timer.schedule(new Ani(), 0);
		}
	}

	/**
	 * Stops a text effect
	 */
	public synchronized void stop() {
		if (doEffect) {
			doEffect = false;
			timer.cancel();
			timer = null;
		}
	}
}
